package cn.zhxu.data.fastjson;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;

import java.lang.reflect.Type;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;

/**
 * LocalDateTime 序列化器
 * @author Troy.Zhou @ 2025-08-28
 * @since v1.7.0
 */
public class TemporalSerializer implements ObjectSerializer {

    private final DateTimeFormatter defaultFormatter;

    public TemporalSerializer(String defaultFormat) {
        defaultFormatter = DateTimeFormatter.ofPattern(defaultFormat);
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) {
        if (object == null) {
            serializer.writeNull();
            return;
        }
        String format = FastjsonDataConvertor.FORMAT_HOLDER.get();
        if (format != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
            serializer.write(formatter.format((TemporalAccessor) object));
        } else {
            serializer.write(defaultFormatter.format((TemporalAccessor) object));
        }
    }

}
